<template>
  <div class="app-container calendar-list-container">
    <basic-container>
      <template>
        <el-tabs @tab-click="switchTab">
          <el-tab-pane label="信息管理" name="userManager"/>
          <el-tab-pane label="密码管理" name="passwordManager"/>
        </el-tabs>
      </template>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form
              v-if="switchStatus==='userManager'"
              ref="ruleForm2"
              :model="ruleForm2"
              :rules="rules2"
              label-width="100px"
              class="demo-ruleForm">
              <el-form-item
                label="登录名"
                key="loginname"
                prop="loginname">
                <el-input
                  v-model="ruleForm2.loginname"
                  type="text"
                  disabled/>
              </el-form-item>
              <el-form-item label="手机号" key="phone" prop="phone">
                <el-input v-model="ruleForm2.phone" placeholder="验证码登录使用"/>
              </el-form-item>
              <el-form-item label="头像" class="avatar-box" key="avatar">
                <el-upload
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  class="avatar-uploader"
                  action="/admin/sys-file/upload">
                  <img v-if="ruleForm2.avatar" id="avatar" :src="avatarUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
                <div class="avatar-warn">图片格式只支持jpg、png格式，大小不得超过500KB。</div>
              </el-form-item>
              <el-form-item
                label="社交登录"
                prop="social">
                <a
                  href="#"
                  style="color: blue"
                  @click="handleClick('wechat')">绑定微信</a>｜
                <a
                  href="#"
                  style="color: blue"
                  @click="handleClick('gitee')">绑定码云</a> |
                <a
                  href="#"
                  style="color: blue"
                  @click="handleClick('osc')">开源中国</a>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="submitForm('ruleForm2')">提交
                </el-button>
                <el-button @click="resetForm('ruleForm2')">重置</el-button>
              </el-form-item>
            </el-form>
            <el-form
              v-if="switchStatus==='passwordManager'"
              ref="ruleForm2"
              :model="ruleForm2"
              :rules="rules2"
              label-width="100px"
              class="demo-ruleForm">
              <el-form-item
                label="原密码"
                key="password"
                prop="password">
                <el-input
                  v-model="ruleForm2.password"
                  type="password"
                  auto-complete="off"/>
              </el-form-item>
              <el-form-item
                label="密码"
                key="newpassword1"
                prop="newpassword1">
                <el-input
                  v-model="ruleForm2.newpassword1"
                  type="password"
                  auto-complete="off"/>
              </el-form-item>
              <el-form-item
                label="确认密码"
                key="newpassword2"
                prop="newpassword2">
                <el-input
                  v-model="ruleForm2.newpassword2"
                  type="password"
                  auto-complete="off"/>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="submitPwd('ruleForm2')">提交
                </el-button>
                <el-button @click="resetForm('ruleForm2')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </basic-container>
  </div>
</template>

<script>
  import {handleImg, openWindow} from '@/util/util'
  import {mapState} from 'vuex'
  import store from '@/store'
  import {getStore, setStore} from '@/util/store'
  import {editInfo,updateUserPwd} from '@/api/admin/user'
  import { isvalidatemobile,validateStr } from '@/util/validate'
  import {encryption} from '@/util/util'


  export default {
    data() {
      const validatePass = (rule, value, callback) => {
        if (this.ruleForm2.password !== '') {
          if (value !== this.ruleForm2.newpassword1) {
            callback(new Error('两次输入密码不一致!'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      const validatePhone = (rule, value, callback) => {
        if (isvalidatemobile(value)[0]) {
          callback(new Error(isvalidatemobile(value)[1]))
        } else {
          callback()
        }
      }
      const validatePsd = (rule, value, callback) => {
        if (validateStr(value)[0]) {
          callback(new Error(validateStr(value)[1]))
        } else {
          callback()
        }
      }
      return {
        switchStatus: 'userManager',
        avatarUrl: '',
        show: false,
        headers: {
          'Authorization': 'Bearer ' + store.getters.access_token,
        },
        ruleForm2: {
          loginname: '',
          password: '',
          newpassword1: '',
          newpassword2: '',
          avatar: '',
          phone: ''
        },
        rules2: {
          phone: [{required: true, validator: validatePhone, trigger: ['blur','change']}],
          password: [{required: true, min: 1, message: '原密码不能为空且不少于1位', trigger: 'blur'}],
          newpassword1: [
            {required: true,min: 1,max: 50, message: '新密码不能为空且长度在1到50个字符', trigger: 'blur'},
          //  { validator: validatePsd, trigger: 'blur'},
          ],
          newpassword2: [
            {required: true, message: '确认密码不能为空', trigger: 'blur'},
            {validator: validatePass, trigger: 'blur'}
          ]
        }
      }
    },
    created() {
      this.resetForm()
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo
      })
    },

    methods: {
      switchTab(tab) {
        if (tab.name === 'userManager') {
          handleImg(this.ruleForm2.avatar, 'avatar')
        }
        this.switchStatus = tab.name
      },
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (!valid) {
            return false
          }
          const user = JSON.parse(JSON.stringify(this.ruleForm2))
          editInfo(user).then(response => {
            this.handleLocalData(this.ruleForm2)
            this.$notify.success('修改成功')
            handleImg(this.userInfo.avatar, 'thumbnail')
          })
        })
      },
	  submitPwd(formName) {
	    this.$refs[formName].validate(valid => {
	      if (!valid) {
	        return false
	      }
	      const user = encryption({
	        data: this.ruleForm2,
	        key: 'scaxscaxscaxscax',
	        param: ['password', 'newpassword1', 'newpassword2']
	      })
        user.userId= this.userInfo.id;
	      updateUserPwd(user).then(response => {
	        this.$notify.success('修改成功')
	        // 修改密码之后强制重新登录
	        if (this.switchStatus === 'passwordManager') {
	          this.$store.dispatch('LogOut').then(() => {
	            location.reload() // 为了重新实例化vue-router对象 避免bug
	          })
	        }
	      })
	    })
	  },
      resetForm() {
        this.ruleForm2.password = undefined
        this.ruleForm2.newpassword1 = undefined
        this.ruleForm2.newpassword2 = undefined
        this.ruleForm2.loginname = this.userInfo.username
        this.ruleForm2.phone = this.userInfo.phone
        this.ruleForm2.avatar = this.userInfo.avatar
        handleImg(this.userInfo.avatar, 'avatar')
        //判断是否选择了租户ID
        const TENANT_ID = getStore({name: 'tenantId'})
        if (TENANT_ID) {
          this.headers['TENANT-ID'] = TENANT_ID // 租户ID
        }
      },
      handleClick(thirdpart) {
        let appid, client_id, redirect_uri, url
        redirect_uri = encodeURIComponent(window.location.origin + '/#/authredirect')
        if (thirdpart === 'wechat') {
          appid = 'wxd1678d3f83b1d83a'
          url = 'https://open.weixin.qq.com/connect/qrconnect?appid=' + appid + '&redirect_uri=' + redirect_uri + '&state=WX-BIND&response_type=code&scope=snsapi_login#wechat_redirect'
        } else if (thirdpart === 'tencent') {
          client_id = '101322838'
          url = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&state=QQ-BIND&client_id=' + client_id + '&redirect_uri=' + redirect_uri
        } else if (thirdpart === 'gitee') {
          client_id = '235ce26bbc59565b82c989aa3a407ce844cf59a7c5e0f9caa9bb3bf32cee5952'
          url = 'https://gitee.com/oauth/authorize?response_type=code&state=GITEE-BIND&client_id=' + client_id + '&redirect_uri=' + redirect_uri
        } else if (thirdpart === 'osc') {
          client_id = 'neIIqlwGsjsfsA6uxNqD'
          url = 'https://www.oschina.net/action/oauth2/authorize?response_type=code&client_id=' + client_id + '&state=OSC-BIND&redirect_uri=' + redirect_uri
        }
        openWindow(url, thirdpart, 540, 540)
      },
      //头像上传前
      beforeAvatarUpload(file){
        const isJPG = file.type === 'image/jpeg';
        const isPng = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 0.5;

        if (!isJPG && !isPng) {
          this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 500KB!');
        }
        return (isJPG || isPng ) && isLt2M;
      },
      handleAvatarSuccess(res, file) {
        this.avatarUrl = URL.createObjectURL(file.raw)
        this.ruleForm2.avatar = res.data.url
      },
      // 处理本地数据，避免刷新不同步
      handleLocalData(form) {
        let userInfo = getStore({name: 'userInfo'})

        if (userInfo) {
          userInfo.avatar = form.avatar
          userInfo.phone = form.phone
          setStore({
            name: 'userInfo',
            content: userInfo,
            type: 'session'
          })
        }
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px !important;
    color: #8c939d !important;
    width: 178px !important;
    height: 178px !important;
    line-height: 178px !important;
    text-align: center !important;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<style lang="scss" scoped>
  .avatar-box{
    .avatar-warn{
      color: #999;
    }
  }
</style>
